#include <QObject>
#include <QEvent>
#include <QTableWidget>
#include <QMenu>
#include <QAction>
#include <QDebug>
#include <QContextMenuEvent>
class TableMenuFilter : public QObject {
    Q_OBJECT
public:
    explicit TableMenuFilter(QTableWidget *table, QObject *parent = nullptr)
        : QObject(parent), table(table) {}



signals:
    void create_trig(int,int);
    void copy_trig(int,int);
    void edit_trig(int,int);
    void move_trig(int,int);
    void connect_trig(int,int);
    void delete_trig(int,int);

protected:
    bool eventFilter(QObject *obj, QEvent *event) override {
        if (obj == table && event->type() == QEvent::ContextMenu) {
            QContextMenuEvent *contextEvent = static_cast<QContextMenuEvent*>(event);
            
            // 获取鼠标位置对应的单元格
//            int row = table->rowAt(contextEvent->pos().y());
//            int col = table->columnAt(contextEvent->pos().x());
            QModelIndex index = table->indexAt(contextEvent->pos());
            int row = index.row();    // 从索引中获取行号
            int col = index.column(); // 从索引中获取列号

            row--; //删除表头代表的索引
            col--;
            // 创建右键菜单
            QMenu menu(table);
            QAction *createEdit = menu.addAction("新建器件");
            QAction *actionEdit = menu.addAction("编辑器件");
            QAction *actionCopy = menu.addAction("复制器件");
            QAction *actionMove = menu.addAction("移动器件");
            QAction *actionConnect = menu.addAction("连接器件");
            QAction *actionDelete = menu.addAction("删除器件");

            // 禁用无效操作
            if (row < 0 || col < 0) {
                createEdit->setEnabled(false);
                actionEdit->setEnabled(false);
                actionCopy->setEnabled(false);
                actionMove->setEnabled(false);
                actionConnect->setEnabled(false);
                actionDelete->setEnabled(false);
            }
            // 显示菜单并处理选择
            QAction *selectedAction = menu.exec(contextEvent->globalPos());
            if(selectedAction == createEdit) {
                emit create_trig(row,col);
            } else if (selectedAction == actionEdit) {
                //qDebug() << "编辑单元格:" << row << "," << col;
                emit edit_trig(row,col);
            } else if (selectedAction == actionCopy) {
                //qDebug() << "复制单元格:" << row << "," << col;
                emit copy_trig(row,col);
            } else if (selectedAction == actionMove) {
                emit move_trig(row,col);
            } else if(selectedAction == actionConnect) {
                emit connect_trig(row,col);
            } else if(selectedAction == actionDelete){
                emit delete_trig(row,col);
            }
            
            return true; // 事件已处理
        }
        
        // 其他事件交给默认处理
        return QObject::eventFilter(obj, event);
    }

private:
    QTableWidget *table;
};

